package com.jinxin.platform.cdacscontrolmgr.service.impl;

import com.jinxin.platform.base.common.pojo.JsonResult;
import com.jinxin.platform.cdacscontrolmgr.bean.CdacscontrolmgrOwner;
import com.jinxin.platform.cdacscontrolmgr.bean.CdparkmanagerProjectAccess;
import com.jinxin.platform.cdacscontrolmgr.bean.bo.ProjectInfo;
import com.jinxin.platform.cdacscontrolmgr.common.Constant;
import com.jinxin.platform.cdacscontrolmgr.mapper.CdacscontrolmgrOwnerMapper;
import com.jinxin.platform.cdacscontrolmgr.mapper.CdacscontrolmgrProjectAccessMapper;
import com.jinxin.platform.cdacscontrolmgr.mapper.CdacscontrolmgrProjectMapper;
import com.jinxin.platform.cdacscontrolmgr.rpc.CdacscontrolmgrRpc;
import com.jinxin.platform.cdacscontrolmgr.service.ICdacscontrolkmgrOwnerService;
import com.jinxin.platform.cdacscontrolmgr.utils.DateUtil;
import com.jinxin.platform.cdacscontrolmgr.utils.IdWorker;
import com.jinxin.platform.cdacscontrolmgr.utils.ImageUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;
import sun.misc.BASE64Encoder;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;

/**
 * All rights Reserved, Designed By www.beonelot.com
 *
 * @version: V1.0
 * @Copyright: www.beonelot.com Inc. All rights reserved.
 * @Description：
 * @Date: 2021-09-06
 * @Author: Lingnan
 **/
@Service
@Slf4j
public class CdacscontrolkmgrOwnerServiceImpl implements ICdacscontrolkmgrOwnerService {
    @Autowired
    CdacscontrolmgrOwnerMapper cdacscontrolmgrOwnerMapper;
    @Resource
    private IdWorker idWorker;
    @Autowired
    private CdacscontrolmgrRpc cdacscontrolmgrRpc;
    @Autowired
    private CdacscontrolmgrProjectMapper cdacscontrolmgrProjectMapper;
    @Autowired
    private CdacscontrolmgrProjectAccessMapper projectAccessMapper;
    @Value(value = "${platform.upload}")
    private String filePath;

    @Override
    public CdacscontrolmgrOwner selectOne(HashMap param) {
        return cdacscontrolmgrOwnerMapper.selectOne(param);
    }

    @Override
    public List<CdacscontrolmgrOwner> list(HashMap param) {
        return cdacscontrolmgrOwnerMapper.list(param);
    }

    @Override
    public List<CdacscontrolmgrOwner> listPage(HashMap param) {
        return cdacscontrolmgrOwnerMapper.listPage(param);
    }

    @Override
    public int listPageCount(HashMap param) {
        return cdacscontrolmgrOwnerMapper.listPageCount(param);
    }

    @Override
    public JsonResult delete(String id) {
        if(StringUtils.isEmpty(id)){
            return JsonResult.error("Id不存在");
        }
        CdacscontrolmgrOwner owner = cdacscontrolmgrOwnerMapper.selectByKey(id);
        if(owner == null){
            return JsonResult.error("业主不存在");
        }
        JsonResult jsonResult = cdacscontrolmgrRpc.deletePortraitData(id,owner.getProjectId());
        if(jsonResult.getSuccess()){
            int result = cdacscontrolmgrOwnerMapper.deleteByKey(id);
            if(result > 0){
                return JsonResult.ok("删除成功","");
            }
            return JsonResult.error("删除失败");
        }
        return JsonResult.error("删除失败,原因是:"+jsonResult.getMsg());
    }

    @Override
    public JsonResult saveOrUpdate(CdacscontrolmgrOwner record, MultipartFile file) {
        if (record == null){
            return JsonResult.error("参数错误，操作失败");
        }
        HashMap param = new HashMap();
        String projectId = record.getProjectId();
        param.put("projectId", projectId);
        List<CdparkmanagerProjectAccess> list = projectAccessMapper.list(param);
        String id = record.getId();
        int count = 0;
        String msg = "";
        boolean flag = false;
        String startTime = DateUtil.getCurrentDayYMD("yyyy/MM/dd HH:mm:ss");
        if(!file.isEmpty()){
            try {
                String filename = file.getOriginalFilename();
                String fileType = filename.substring(filename.lastIndexOf(".")+1);
                String prefix = ImageUtils.getPreTypeByImgType(fileType);
                String faceBytes;
                if(file.getSize() > 200*1024){
                    byte[] bytes = ImageUtils.commpressPicCycle(file.getBytes(), 200, 0.5f);
                    BASE64Encoder encoder = new BASE64Encoder();
                    faceBytes = encoder.encode(bytes).replaceAll("\r|\n", "");
                }else {
                    faceBytes = ImageUtils.multipartFileToBase64(this.filePath,file);
                }
                record.setFaceInfo(prefix + faceBytes);
            }catch (Exception e){
                log.error("压缩转换图片失败，" + e.toString());
                return JsonResult.error("压缩图片失败");
            }
        }
        if(StringUtils.isEmpty(id)){
            String personId = String.valueOf(idWorker.nextId());
            record.setId(personId);
            // 上传人脸信息
            for(CdparkmanagerProjectAccess item : list){
                String faceMac = item.getFaceMac();
                JsonResult jsonResult = cdacscontrolmgrRpc.uploadPortraitData(personId, record.getName(), "1", "0", record.getFaceInfo(), startTime, Constant.FOREVER_TIME, personId, faceMac);
                if(jsonResult.getSuccess()){
                    if(!flag){
                        int n = cdacscontrolmgrOwnerMapper.insert(record);
                        if(n > 0){
                            flag = true;
                        }
                        count += n;
                        msg = "新增成功";
                    }
                }else {
                    msg = jsonResult.getMsg();
                }
            }
        }else {
            JsonResult jsonResult = cdacscontrolmgrRpc.deletePortraitData(id,projectId);
            if(jsonResult.getSuccess()){
                for(CdparkmanagerProjectAccess item : list){
                    JsonResult jsonResult2 = cdacscontrolmgrRpc.uploadPortraitData(id, record.getName(), "1", "0",
                            record.getFaceInfo(), startTime, Constant.FOREVER_TIME, id, item.getFaceMac());
                    if(jsonResult2.getSuccess()){
                        if(!flag){
                            int i = cdacscontrolmgrOwnerMapper.updateByKey(record);
                            if(i > 0){
                                flag = true;
                                msg = "更新成功";
                            }
                            count += i;
                        }
                    }else {
                        msg = jsonResult2.getMsg();
                    }
                }
            }else {
                msg = jsonResult.getMsg();
            }
        }
        if(count > 0){
            return JsonResult.ok(msg,"");
        }else {
            return JsonResult.error(msg);
        }
    }

    @Override
    public List<ProjectInfo> queryProjectByPhone(String phone) {
        if(StringUtils.isEmpty(phone)){return null;}
        HashMap param = new HashMap();
        param.put("phone",phone);
        List<String> idList = new ArrayList<>();
        List<CdacscontrolmgrOwner> list = cdacscontrolmgrOwnerMapper.list(param);
        Map<String,CdacscontrolmgrOwner> roomOwnerMap = new HashMap<>();
        list.forEach(item->{
            String projectId = item.getProjectId();
            idList.add(projectId);
            roomOwnerMap.put(projectId,item);
        });
        List<ProjectInfo> projectInfos = new ArrayList<>();
        if(idList.size() > 0){
            projectInfos = cdacscontrolmgrProjectMapper.selectByIdSet(idList);
            projectInfos.forEach(p->{
                CdacscontrolmgrOwner owner = roomOwnerMap.get(p.getId());
                p.setRoomNo(owner.getRoomNo());
                p.setOwner(owner.getName());
            });
        }
        return projectInfos;
    }
}
